<template>
  <el-drawer v-model="dialogVisible" :title="parameter.title" destroy-on-close size="80%">
    <div class="table-box">
      <pro-table ref="proTableRef" row-key="id" :columns="columns" :init-param="initParam" :request-api="getSequenceRulePageApi">
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button v-auth="'sys:sequence:addRule'" type="primary" :icon="CirclePlus" @click="handleAdd"> 新增规则 </el-button>
        </template>
        <!-- 规则参数 -->
        <template #ruleValue="{ row }">
          {{ row.ruleValue || "--" }}
        </template>
        <!-- 填充字符 -->
        <template #paddingChar="{ row }">
          {{ row.paddingChar || "--" }}
        </template>
        <!-- 状态 -->
        <template #isEnable="scope">
          <el-switch
            v-model="scope.row.isEnable"
            :loading="scope.row.loading"
            active-text="已启用"
            inactive-text="已禁用"
            inline-prompt
            :before-change="handleEnable.bind(scope, scope.row)"
          />
        </template>
        <!-- 菜单操作 -->
        <template #operation="{ row }">
          <el-button v-auth="'sys:sequence:editRule'" type="primary" link :icon="EditPen" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button v-auth="'sys:sequence:delRule'" type="danger" link :icon="Delete" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </pro-table>

      <!-- 编辑序列规则 -->
      <sequence-rule-edit ref="editDialogRef" />
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import type { SysSequenceRule } from "@/api/interface";
import { ref, reactive } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import { statusConst, sequenceRuleTypeConst, sequencePaddingSideConst } from "@/utils/dict";
import {
  addSequenceRuleApi,
  editSequenceRuleApi,
  switchEnableSequenceRuleApi,
  deleteSequenceRuleApi,
  getSequenceRulePageApi
} from "@/api/modules/system/sequencerule";
import { Delete, EditPen, CirclePlus } from "@element-plus/icons-vue";
import { FormEnum } from "@/enums/formEnum";
import ProTable from "@/components/ProTable/index.vue";
import SequenceRuleEdit from "@/views/system/sequenceManage/components/editRule.vue";

defineOptions({
  name: "SystemSequenceRule"
});

/** 序列规则 */
interface EditProps {
  /** 标题 */
  title: string;
  /** 序列Id */
  sequenceId: string;
}

/** 表格实例 */
const proTableRef = ref<ProTableInstance>();
/** 编辑弹窗实例 */
const editDialogRef = ref<InstanceType<typeof SequenceRuleEdit> | null>(null);

/** dialog 状态 */
const dialogVisible = ref(false);
/** 父组件传过来的参数 */
const parameter = ref<EditProps>({
  title: "",
  sequenceId: FormEnum.EmptyId
});
/** 表单初始化参数 */
const initParam = reactive({ sequenceId: "", orderField: "ruleOrder", isAscending: true });
/** 表格配置项 */
const columns: ColumnProps[] = [
  { prop: "ruleOrder", label: "排序", width: 90 },
  { prop: "ruleType", label: "规则类别", width: 160, enum: sequenceRuleTypeConst },
  { prop: "ruleValue", label: "规则参数", width: 120 },
  { prop: "paddingSide", label: "补齐方向", width: 120, enum: sequencePaddingSideConst },
  { prop: "paddingWidth", label: "补齐宽度", width: 120 },
  { prop: "paddingChar", label: "填充字符", width: 120 },
  { prop: "description", label: "描述(说明)" },
  { prop: "isEnable", label: "状态", width: 100, enum: statusConst, search: { el: "select" } },
  { prop: "operation", label: "操作", width: 180, fixed: "right" }
];

/**
 * 接收父组件参数
 *
 * @param params 父组件传过来的参数
 * @returns void
 */
const acceptParams = (params: EditProps) => {
  parameter.value = params;
  initParam.sequenceId = params.sequenceId;
  dialogVisible.value = true;
};

/**
 * 添加序列规则
 *
 * @returns void
 */
const handleAdd = () => {
  const editParams = {
    title: "添加序列",
    rule: {
      sequenceId: initParam.sequenceId,
      ruleOrder: 1
    },
    getTableList: proTableRef.value?.getTableList,
    submitApi: addSequenceRuleApi
  };
  editDialogRef.value?.acceptParams(editParams);
};

/**
 * 编辑序列规则
 *
 * @param param 选中的序列规则
 * @returns void
 */
const handleEdit = (param: Partial<SysSequenceRule.Result>) => {
  const editParams = {
    title: "编辑序列规则",
    rule: { ...param },
    getTableList: proTableRef.value?.getTableList,
    submitApi: editSequenceRuleApi
  };
  editDialogRef.value?.acceptParams(editParams);
};

/**
 * 启用/禁用序列规则
 *
 * @param param 选中的序列规则
 * @returns void
 */
const handleEnable = (param: Partial<SysSequenceRule.Result> & { loading?: boolean }) => {
  param.loading = true;
  return switchEnableSequenceRuleApi({ id: param.id! })
    .then(({ data }) => {
      if (data) {
        return Promise.resolve(true);
      } else return Promise.reject(new Error("修改状态失败"));
    })
    .finally(() => {
      param.loading = false;
    });
};

/**
 * 删除序列规则
 *
 * @param param 选中的序列规则
 * @returns void
 */
const handleDelete = (param: Partial<SysSequenceRule.Result>) => {
  useHandleData(deleteSequenceRuleApi, { ids: [param.id] }, `删除【${param.sequenceName}】序列规则`).then(res => {
    if (res) proTableRef.value?.getTableList();
  });
};

// 暴露给父组件的属性和方法
defineExpose({
  acceptParams
});
</script>
